//
//  EmoticonViewContr.swift
//  表情键盘
//
//  Created by waterfoxjie on 15/8/9.
//  Copyright © 2015年 zj. All rights reserved.
//

import UIKit

let ZJEmoticonCollectionCellID = "ZJEmoticonCollectionCellID"

class EmoticonViewContr: UIViewController {
    
    // MARK: - 定义一个选择表情的闭包
    var selectEmoticonsCallBack : (emoticon : Emoticon) -> ()
    
    // 写一个构造方法，来初始化这个闭包
    //  (emoticon : Emoticon) -> () 这是参数的类型
    init(selectEmoticon :  (emoticon : Emoticon) -> ()) {
    
        // 记录闭包
        selectEmoticonsCallBack = selectEmoticon
        
        // 调用父类默认构造函数
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // MARK: - toolbar按钮监听方法
    func clickItem(item : UIBarButtonItem) {
        
        // forItem ：滚动到第几页   inSection ：滚动到对应的按钮的组
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
    
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
    

    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        setUpUI()

        
    }
    
    // MARK: - 搭建界面
    private func setUpUI() {
        
        toolbar.tintColor = UIColor.darkGrayColor()
    
        // 添加控件
        view.addSubview(toolbar)
        
        view.addSubview(collectionView)
        
        // 自动布局
        let viewDict = ["cv" : collectionView , "tb" : toolbar]
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        
        // V:|-0-[cv]-0-[tb(44)]-0-| 表示：cv距顶部边距0，距tb控件44，tb控件距底部边距0
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        
        // 准备控件
        perparToolbar()
        
        perparCollectionView()
        
    }
    
    // MARK: - 设置collectionView
    private func perparCollectionView() {
        
        // 注册cell
        collectionView.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: ZJEmoticonCollectionCellID)
    
        // 设置数据源
        collectionView.dataSource = self
        
        // 设置代理
        collectionView.delegate = self
        
        
    }
    
    
    // MARK: - 给toolbar添加控件
    private func perparToolbar() {
        
        var items = [UIBarButtonItem]()
        
        var idnex = 0
        
        // 添加头部固定弹簧
        items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil))
    
        for p in packages {
            
            print(p.groupName)
        
            items.append(UIBarButtonItem(title: p.groupName, style: UIBarButtonItemStyle.Plain, target: self, action: "clickItem:"))
            
            items.last?.tag = idnex++
            
            // 添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
        }
        
        // 删除最后一个
        items.removeLast()
        
        // 添加尾部固定弹簧
        items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil))
        
        toolbar.items = items
        
    }
    
    // MARK: - 懒加载
    // 表情包数据
    private lazy var packages = EmoticonPackage.package()
    
    // toolbar控件
    private lazy var toolbar : UIToolbar = UIToolbar()
    
    // collectionView
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonCellLayout())
    
    // MARK: - 设置collectionCell的自动布局
    // 私有类，类中类
    private class EmoticonCellLayout : UICollectionViewFlowLayout {
    
        // 自动布局的方法
        private override func prepareLayout() {
            
            // 每个cell的宽度
            let w = collectionView!.bounds.width / 7.0
            
            // 设置整个cell垂直居中
            // 这里如果写0.5的话，iphone4s会只显示2行，所以设置0.499
            let y = (collectionView!.bounds.height - 3 * w) * 0.499
            
            // 设置上下左右的间距
            sectionInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
            
            itemSize = CGSize(width: w, height: w)
            
            minimumInteritemSpacing = 0
            
            minimumLineSpacing = 0
            
            // 设置分页、水平滑动
            scrollDirection = UICollectionViewScrollDirection.Horizontal
            
            collectionView?.pagingEnabled = true
            
            collectionView?.showsHorizontalScrollIndicator = false
            
        }
        
    }
    
}

// MARK: - 实现数据源、代理方法
extension EmoticonViewContr : UICollectionViewDataSource , UICollectionViewDelegate {
    
    // 代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 获取当前选中的表情
        let emoticon = packages[indexPath.section].emoticons![indexPath.item]
        
        // 做完成回调
        selectEmoticonsCallBack(emoticon: emoticon)
        
    }
    
    // 返回分组数量（表情包数量）
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return packages.count
    }

    // 返回每个表情包中表情的数量
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return packages[section].emoticons?.count ?? 0
        
    }
    
    // cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ZJEmoticonCollectionCellID, forIndexPath: indexPath) as! EmoticonCell
        
        cell.backgroundColor = (indexPath.item % 2 == 0) ? UIColor.redColor() : UIColor.greenColor()
        
        cell.emoticons = packages[indexPath.section].emoticons![indexPath.item]
        
        return cell
    }

}

// MARK: - 自定义cell
private class EmoticonCell : UICollectionViewCell {
    
    // 添加一个表情数组属性
    var emoticons : Emoticon? {
    
        didSet {
        
            // 设置图像
            btn.setImage(UIImage(contentsOfFile: emoticons!.imagePath), forState: UIControlState.Normal)
            
            // 设置emoji
            btn.setTitle(emoticons?.emoji, forState: UIControlState.Normal)
            
            // 判断是不是删除按钮，是则，添加删除图片
            if emoticons!.removeEmoticon {
            
                btn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                
                btn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
            
        }
    }
    
    // 构造函数
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        btn.backgroundColor = UIColor.whiteColor()
        
        // CGRectInset(bounds, 4, 4)表示相对于bounds向内缩进4
        btn.frame = CGRectInset(bounds, 4, 4)
        
        // 设置按钮字体。调整emoji图标的大小
        btn.titleLabel?.font = UIFont.systemFontOfSize(32)
        
        // 设置按钮不能与用户进行交互
        btn.userInteractionEnabled = false
        
        // 添加控件
        addSubview(btn)
        
    }

    required init?(coder aDecoder: NSCoder) {
        
        fatalError("init(coder:) has not been implemented")
    }

    // 懒加载控件
    private lazy var btn = UIButton()

    
}




